package com.mark.dao.split;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.keygen.SelectKeyGenerator;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.mapping.SqlCommandType;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.Locale;
import java.util.Properties;

/**
 * Created by Choisaaaa on 2018/4/24.
 */

@Slf4j
@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }),
              @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }) })
public class DynamicDataSourceInterceptor implements Interceptor{
    private static final String REGEX = ".*insert\\u0020.*|.*delete\\u0020.*|.*update\\u0020.*";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        boolean synchronizationActive = TransactionSynchronizationManager.isActualTransactionActive();//判断使用事务的方式
        Object[] objects = invocation.getArgs();
        MappedStatement ms = (MappedStatement) objects[0];
        String lookupKey = DynamicDataSourceHolder.DB_MASTER;
        if (synchronizationActive != true) {
            // 读方法
            if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {

                if (ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)) {// selectKey 为自增id查询主键(SELECT LAST_INSERT_ID())方法，使用主库
                    lookupKey = DynamicDataSourceHolder.DB_MASTER;
                } else {
                    BoundSql boundSql = ms.getSqlSource().getBoundSql(objects[1]);
                    String sql = boundSql.getSql().toLowerCase(Locale.CHINA).replaceAll("[\\t\\n\\r]", " ");
                    if (sql.matches(REGEX)) {//如果是增删改操作交给master
                        lookupKey = DynamicDataSourceHolder.DB_MASTER;
                    } else {//其他的操作：query交给slave
                        lookupKey = DynamicDataSourceHolder.DB_SLAVE;
                    }
                }
            }
        } else {//使用事务的方法交给master数据库
            lookupKey = DynamicDataSourceHolder.DB_MASTER;
        }
        log.debug("设置方法[{}] use [{}] Strategy, SqlCommentType [{}]", ms.getId(), lookupKey,
                ms.getSqlCommandType().name());
        DynamicDataSourceHolder.setDBType(lookupKey);//设置使用的数据库类型
        return invocation.proceed();

    }

    //返回拦截的对象
    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {//Executor是用来支持增删改查操作的对象
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }


    //类初始化的时候相关的设置
    @Override
    public void setProperties(Properties properties) {

    }
}
